package hall

import (
	"container/list"
	"reflect"
	"time"

	"webgame/internal/model/entity/hall"
	"webgame/pkg/queue"
	"webgame/pkg/utils"

	"github.com/topfreegames/pitaya/v2/component"
	"github.com/topfreegames/pitaya/v2/logger"
)

var typeOfLoginInfo = reflect.TypeOf(&hall.LoginInfo{})

// 排队进程(若超过最大连接数，就会排队登录)
type LoginThread struct {
	component.LogicThread
	waitLoginQueue *queue.BaseQueue
	waitLoginMap   map[string]*list.Element
	workerPool     *RemoteLoginThreadPool
}

func NewLoginThread() *LoginThread {
	l := &LoginThread{
		waitLoginQueue: queue.NewBaseQueue(typeOfLoginInfo),
		waitLoginMap:   map[string]*list.Element{},
		workerPool: &RemoteLoginThreadPool{
			loginChan: make(chan *hall.LoginInfo),
			workers:   []component.LogicThread{},
		},
	}
	//Thread Comp回定时call run()
	l.Run = func() {
		sleepTime := 100
		beginExecuteTime := utils.Now()
		LoginManager.Tick(beginExecuteTime)
		if l.waitLoginQueue.Size() == 0 {
			//
			// accountInfo := model.Users{Username: "test2", Password: "111"}
			// rs, err := dao.UserDataDao.Get(&accountInfo)
			// fmt.Println("rs:", rs)
			// fmt.Println("err:", err)
			//
			sleepTime = 1000
		} else {
			//可以登录到登录管道的人数
			canEnterRemoteLoginChanNum := l.getCanEnterLoginChanNum()
			if canEnterRemoteLoginChanNum > 0 {
				l.workerPool.doRemoteLogin(l.waitLoginQueue.Poll().Value.(*hall.LoginInfo))
			} else {
				sleepTime = 500
			}

			//
			l.dealWithCloseQueue(l.waitLoginQueue)
			endExecuteTime := utils.Now()
			executeTime := endExecuteTime - beginExecuteTime
			logger.Log.Debugf("线程%s，执行时长：%d，本轮可允许登录玩家数量：%d", l.GetName(), executeTime, canEnterRemoteLoginChanNum)
			time.Sleep(time.Duration(sleepTime) * time.Millisecond)
		}
	}
	return l
}

// 初始化创建两个服务
// 1:排队服务logicThead
// 2:接收队列remoteLoginTread
func (l *LoginThread) Init() {
	l.LogicThread.Init()
	l.workerPool.Init()
}

func (l *LoginThread) Shutdown() {
	l.LogicThread.Shutdown()
	l.workerPool.Shutdown()
}

// 登录请求进去queue
func (l *LoginThread) AddNewLoginMsg(info *hall.LoginInfo) error {

	l.waitLoginMap[info.SessionId] = l.waitLoginQueue.Offer(info)

	return nil
}

// 获取可以进入登录队列的人数
func (l *LoginThread) getCanEnterLoginChanNum() int {
	//正在登录玩家的人数
	//已经登录的玩家人数（登录服 + 游戏服上玩家总数
	//当前可以登录的玩家人数
	return 10000
}

// 移除关闭session的登录
func (l *LoginThread) dealWithCloseQueue(waitLoginQueue *queue.BaseQueue) error {
	return nil
}
